<template>
  <div class="main">
    <div class="search">
      <el-form :inline="true" :model="search">
        <el-form-item>
          <el-button type="success" size="small" @click="resetproductInfoForm(); dialogShow = true">添加</el-button>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="search.adName" size="small" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="search.adUserName" size="small" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="search.adPhone" size="small" placeholder="联系电话" clearable></el-input>
        </el-form-item>
        <!--        <el-form-item label="备注">-->
        <!--          <el-input v-model="search.description" size="small" placeholder="备注" clearable></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="info" size="small" @click="searchClick">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="list">
      <el-table
          :data="data"
          stripe
          style="width: 100%">
        <el-table-column prop="productName" label="项目名称"></el-table-column>
        <el-table-column prop="model" label="型号"></el-table-column>
        <el-table-column prop="approvalOpinion" label="状态">
<!--          <template slot-scope="scope">-->
<!--            {{getStateMsg(scope.row.reprotStatus)}}-->
<!--          </template>-->
        </el-table-column>
        <el-table-column label="操作" width="170px">
          <template slot-scope="scope">
            <el-button type="primary" @click="productInfoForm = {...scope.row}; dialogShow = true; loadPdf();">审核</el-button>
<!--            <el-button type="danger" @click="del(scope.row.adId)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog
        title="审核"
        :visible.sync="dialogShow"
        width="600px"
        fullscreen
        @close="dialogClose"
    >
      <doc-preview url="/manual.docx"></doc-preview>
      <el-form ref="form" :model="productInfoForm" label-width="100px" :rules="rules">
        <el-form-item prop="reprotStatus" label="审核状态">
          <el-radio-group v-model="productInfoForm.reprotStatus">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="auditOpinion" label="审核意见">
          <el-input type="textarea" placeholder="请输入审核意见" v-model="productInfoForm.auditOpinion"/>
        </el-form-item>
        <el-form-item prop="signature" label="审核人签名">
          <electronic-signatures :value="productInfoForm.signature" @change="reportWriteChange($event, productInfoForm, 'signature')"></electronic-signatures>
        </el-form-item>
        <!--        <el-form-item prop="description" label="备注">-->
        <!--          <el-input type="textarea" placeholder="请输入备注" v-model="productInfoForm.description"/>-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" @click="productInfoSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {httpBaseUrl} from "../util/globa";
import '@wangeditor/editor/dist/css/style.css'
import {getToken} from "../util/auth";
import DocPreview from "../components/DocPreview.vue";
import pdf from "vue-pdf";
import ElectronicSignatures from "@/components/ElectronicSignatures.vue";

export default {
  name: "Admin",
  components: {ElectronicSignatures, DocPreview},
  data() {
    return {
      editor: null,
      toolbarConfig: {
      },
      editorConfig: {
        placeholder: '请输入内容...'
      },
      search: {},
      dialogShow: false,
      productInfoForm: {
        reportConditionVo: [{}],
        reportCheckResultVo: [{}],
        reportSampleSonsResultsVo: [{}],
        reportSampleSafetyResultsVo: [{}],
        reportConsResultsVo: [{}],
        reportSampleSuitResultsVo: [{}],
        reportReliabilityResultVo: [{}],
        reportReliabilityConsResultVo: [{}],
        proTecSpecVo: [{}],
        proCoveredModelVo: [{
          cover: ['']
        }]
      },
      data: [],
      pageNo: 1,
      pageSize: 10,
      total: 0,
      rules: {
        adName: [
          {
            required: true,
            type: 'string',
            message: '用户姓名不能为空',
            trigger: 'blur'
          }
        ],
        adUsername: [
          {
            required: true,
            type: 'string',
            message: '用户名不能为空',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 30,
            message: '用户名长度在3-30位之间',
            trigger: 'blur'
          },
          {
            pattern: /^[0-9A-Za-z_]{3,30}$/,
            message: '用户名只能包含数字、字母、下划线',
            trigger: 'blur'
          },
          // {
          //   validator: (rule, val, cb) => {
          //     let url = `admin/repeat?username=${val}`
          //     if (this.productInfoForm.id) url += `&id=${this.productInfoForm.id}`
          //     this.$http.get(url).then(res => {
          //       if (res.code === 200) {
          //         if (res.data) {
          //           return cb(new Error('用户名已存在！'))
          //         }
          //         cb()
          //       }
          //     })
          //   },
          //   trigger: 'blur'
          // }
        ],
        adPassword: [
          {
            required: false,
            type: 'string',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 30,
            message: '密码长度在6-30位之间',
            trigger: 'blur'
          },
          {
            pattern: /^[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,30}$/,
            message: '密码只能包含数字、字母、特殊字符',
            trigger: 'blur'
          }
        ],
        adPhone: [
          {
            required: true,
            type: 'string',
            message: '电话不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '电话号码格式不正确',
            trigger: 'blur'
          }
        ],
        description: [
          {
            min: 0,
            max: 800,
            message: '备注长度在3-800位之间',
            trigger: 'blur'
          }
        ],
        reprotStatus: [
          {
            required: true,
            type: 'boolean',
            message: '审核状态不能为空',
            trigger: 'blur'
          }
        ]
      },
      baseUrl: httpBaseUrl,
      pdfUrl: '/output.pdf',
      pdfPageTotal: 0
    }
  },
  mounted() {
    this.getData()
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    reportWriteChange(value, form, item) {
      form[item] = value;
    },
    loadPdf() {
      this.$http.post(`/reportApproval/productinfo/getReportFilePath/${this.reportForm.id}`, this.reportForm).then(res => {
        if (res.code === 0) {
          this.pdfUrl = res.path;
          const pdfTask = pdf.createLoadingTask(this.pdfUrl);
          pdfTask.promise.then(pdf => this.pdfPageTotal = pdf.numPages).catch(error => {console.log(error)});
        }
      })
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      const uploadImage = this.editor.getMenuConfig('uploadImage')
      uploadImage.server = '/upload/image'
      uploadImage.fieldName = 'file'
      uploadImage.headers = {
        token: getToken()
      }
      uploadImage.maxFileSize = 10 * 1024 * 1024
      const uploadVideo = this.editor.getMenuConfig('uploadVideo')
      uploadVideo.server = '/upload/video'
      uploadVideo.fieldName = 'file'
      uploadVideo.headers = {
        token: getToken()
      }
      uploadVideo.maxFileSize = 500 * 1024 * 1024
    },
    handleAvatarSuccess(res, file) {
      console.log('======================================');
      console.log(res);
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      return isJPG;
    },
    getToken() {
      return `Bearer ${sessionStorage.getItem('token')}`;
    },
    addItem(array, value = {}) {
      array.push(value);
    },
    delItem(array, index) {
      array.splice(index, 1);
    },
    getData() {
      this.search.page = this.pageNo;
      this.search.limit = this.pageSize;
      this.$http.post(`/reportApproval/productinfo/checklist`, this.search).then(res => {
        if (res.code === 0) {
          this.pageSize = res.page.pageSize
          this.pageNo = res.page.currPage
          this.total = res.page.totalCount
          this.data = res.page.list
        }
      })
    },
    sizeChange(val) {
      this.pageNo = 1;
      this.pageSize = val;
      this.getData();
    },
    currentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    searchClick() {
      this.pageNo = 1;
      this.getData()
    },
    resetproductInfoForm() {
      this.productInfoForm = {
        reportConditionVo: [{}],
        reportCheckResultVo: [{}],
        reportSampleSonsResultsVo: [{}],
        reportSampleSafetyResultsVo: [{}],
        reportConsResultsVo: [{}],
        reportSampleSuitResultsVo: [{}],
        reportReliabilityResultVo: [{}],
        reportReliabilityConsResultVo: [{}],
        proTecSpecVo: [{}],
        proCoveredModelVo: [{
          cover: ['']
        }]
      }
    },
    dialogClose() {
      this.resetForm();
      this.$refs['form'].clearValidate()
    },
    productInfoSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.productInfoForm.adId) {
            this.productInfoForm.adUpdated = null;
            this.productInfoForm.adCreated = null;
            this.$http.post(`/reportApproval/productinfo/updateApprovalOpinion`, this.productInfoForm).then(res => {
              if(res.code === 0) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          }
        }
      });
    },
    submit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.productInfoForm.adId) {
            this.productInfoForm.adUpdated = null;
            this.productInfoForm.adCreated = null;
            this.$http.post(`/reportApproval/admin/update`, this.productInfoForm).then(res => {
              if(res.code === 0) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          } else {
            this.$http.post(`/reportApproval/admin/save`, this.productInfoForm).then(res => {
              if(res.code === 0) {
                this.$Message.success(res.msg)
                this.getData()
                this.dialogShow = false
              }
            })
          }
        }
      });
    },
    del(id) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(id)
        this.$http.post(`/reportApproval/admin/delete`, [id]).then(res => {
          if (res.code === 0) {
            this.getData()
            this.$Message.success(res.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getStateMsg(state) {
      switch (state) {
        case "1": return '用户提交';
        case "2": return '批准人';
        case "3": return '审核人';
        case "4": return '项目负责人';
        case "5": return '下载申报书';
        case "6": return '报告校核人';
        case "7": return '审批通过';
        case "8": return '审批不通过';
        default: return '未知';
      }
    }
  }
}
</script>

<style scoped>

</style>
